<template>
    <Page class="basic company">
        <template #header>
            <el-input v-model="queryForm.merchantName" placeholder="请输入店铺名称"/>
            <EdCascader v-model="queryForm.industryId" :cascaderParams="selectIndustryParams"></EdCascader>
            <EdSelect v-model="queryForm.merchantStatus" :selectParams="merchantStatusParams"></EdSelect>
            <el-date-picker
                v-model="pickerTime"
                type="daterange"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
            <el-button class="ed-button ed_black-bottom" @click="search()"><svg-icon class="svg-middle" icon-class="search-svg"/>查 询</el-button>
            <el-button class="ed-button ed_white_bottom" @click="reset()"><svg-icon icon-class="reset-svg"/>重 置</el-button>
        </template>
        <PageCard title="商家管理列表">
            <template #actions>
                <el-button class="ed-button ed_black-bottom ed-button36" @click="add()"><svg-icon icon-class="add-svg" v-has="'shopping:business:add'" />添加商家</el-button>
            </template>
            <ApiTable :api="load" ref="table" :params="queryForm">
                <el-table-column type="index" width="80" label="序号"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="merchantName" label="店铺名称"/>
                <el-table-column :show-overflow-tooltip="true" prop="address" label="店铺地址"/>
                <el-table-column :show-overflow-tooltip="true" prop="industryName" label="所在行业"/>
                <el-table-column :show-overflow-tooltip="true" prop="mobile" label="手机号"/>
                <el-table-column :show-overflow-tooltip="true" prop="loginName" label="登录账号"/>
                <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建时间"/>
                <el-table-column :show-overflow-tooltip="true" prop="merchantStatus" label="商家状态">
                    <template slot-scope="scope">
                        {{scope.row.merchantStatus == '0' ? '停用' : '启用'}}
                        <el-switch
                            :value="scope.row.merchantStatus == '1' ? true : false"
                            @change="switchChange(scope.row, scope.row.merchantStatus == '1' ? '0' : '1')"
                            active-color="#EED096"
                            inactive-color="#909399">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="" label="操作" width="400px">
                    <template slot-scope="scope">
                        <el-button class="ed-table-bottom ed_black_border" v-has="'shopping:business:update'" @click="updateRow(scope.row)">编辑</el-button>
                        <el-button class="ed-table-bottom ed_blue_border marginRight" v-has="'shopping:business:pay'" @click="payConfigureBut(scope.row)">支付配置</el-button>
                        <el-popconfirm title="确定重置密码吗？" @confirm="resetPwd(scope.$index, scope.row)">
                            <el-button slot="reference" class="ed-table-bottom ed_delete_border marginRight" v-has="'shopping:business:reset'">重置密码</el-button>
                        </el-popconfirm>
                        <el-button class="ed-table-bottom ed_delete_border" v-has="'shopping:business:delete'" @click="del(scope.row)">删除</el-button>
                        
                    </template>
                </el-table-column>
            </ApiTable>
        </PageCard>
        <!-- 商家状态更改接口 -->
        <ed-confirm-delete ref="confirmMerchantStatusRef" @confirmDeleteTrue="confirmMerchantStatuTrue()"></ed-confirm-delete>
        <ed-confirm-delete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue()"></ed-confirm-delete>
        <EdDialog ref="dialogRef" v-if="showPayConfigure" title="支付配置" @close-dialog="closeDialog" @save-dialog="saveDialog">
            <el-form :model="editForm"  ref="ruleForm" :rules="rules" label-position='right' label-width="auto">
                <el-form-item label="商户号" prop="merchantNo" :rules="$validate.validates({required:true,msg:'请输入商户号'})">
                    <el-input v-model="editForm.merchantNo" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="终端号" prop="terminalId" :rules="rules.terminalId" >
                    <el-input v-model="editForm.terminalId" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="令牌" prop="accessToken" :rules="$validate.validates({required:true,msg:'请输入令牌'})" >
                    <el-input v-model="editForm.accessToken" maxlength="50"></el-input>
                </el-form-item>
            </el-form>
        </EdDialog>
    </Page>

</template>

<script>
    import {delMerchant ,merchantList,MerchantStatusGo,MerchantStatusDown,getIndustry,payConfigure,checkPayConfigure} from "./api";
    import { resetpwd } from 'src/api/user'
    import EdTable from "src/components/EdTable.vue";
    import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
    import Page from '../../components/Page.vue'
    import EdDialog from 'src/components/EdDialog.vue'
    import PageCard from 'src/views/components/PageCard.vue'
    import ApiTable from 'src/components/ApiTable.vue'
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCascader from 'src/components/EdCascader.vue'
    import { defineComponent } from 'vue'
    import {getDictByCode} from "src/api/dictionaries";
    export default defineComponent({
        name: "VillageBusinessList",
        components:{
            EdTable,
            EdConfirmDelete,
            Page, PageCard, ApiTable,EdSelect,EdCascader,EdDialog
        },
        data(){
            return{
                 rules: {
                    terminalId: [
                        {required: true, message: '请输入终端号', trigger: 'blur' },
                        {pattern:  /^[a-zA-Z\d+;?]+$/, required: true, message: "只能输入字母和数字,多个终端号请用英文;隔开!", trigger: 'blur' },
                    ],
                 },
                queryForm:{
                    merchantName:"",
                    industryId:'',
                    merchantStatus:'',
                    startTime:'',
                    endTime:''
                },
                pickerTime: [],
                industryParams:{
                    placeholder:"请选择所在行业",
                    options: [],
                    props: {label:"label", value:"value"}
                },
                merchantStatusParams:{
                    placeholder:"请选择商家状态",
                    options: [],
                    props: {label:"label", value:"value"}
                },
                selectIndustryParams:{
                    placeholder:"请选择所在行业",
                    options: [],
                    props: {value: 'id', label: 'name', checkStrictly: false,emitPath:false}
                },
                confirmRow:{},
                confirmMerchantStatusRow:{
                    id:'',
                    merchantStatus:''
                },
                editForm:{
                    merchantNo:'',
                    terminalId:'',
                    accessToken:'',
                    id:''
                },
                showPayConfigure:false,
                data:"商户未开通支付功能，是否执行此操作" ,

            }
        },
        activated(){
            this.$nextTick(()=>{
                this.$refs.table.load(1)
            })

            // 获取字典值方式
            getDictByCode("merchantStatus").then(response => {
                if(response.success) {
                    this.merchantStatusParams.options=response.data.items
                }
            })

            getIndustry().then((res) =>{
                // let arr = [];
                // arr.push(res.data)
                // this.selectIndustryParams.options = arr
                this.$set(this.selectIndustryParams,'options', res.data)
            })
        },
        watch:{
            pickerTime: {
                deep: true,
                immediate: true,
                handler(newVal, oldVal) {
                    // console.log('newVal',newVal,'oldVal',oldVal);
                    if(newVal && newVal.length > 0) {
                        this.queryForm.startTime = newVal[0]
                        this.queryForm.endTime = newVal[1]
                    }
                }
            },
        },
        methods:{
            load:merchantList,
            search(){
                this.$refs.table.load(1)
            },
            add(){
                this.$router.push({
                    path: '/shopping/business-create'
                })
            },
            updateRow(row) {
                this.$router.push({
                    path: '/shopping/business-update',
                    query: { id: row.id,userId:row.userId },
                })
            },
            del(row) {
                this.confirmRow = row;
                this.$refs.confirmDeleteRef.open("删除确认","确认删除此项数据？","warning")
            },
            confirmDeleteTrue(){
                delMerchant({id: this.confirmRow.id}).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: '商户已删除成功！',
                            duration: 2000,
                            center:true
                        });
                        this.$refs.table.load()
                    }
                })
            },
            reset(){
                this.pickerTime=[]
                this.queryForm={
                    merchantName: "",
                    industryId:'',
                    merchantStatus:'',
                    startTime:'',
                    endTime:''
                };
                this.$nextTick(()=>{
                    this.$refs.table.load(1,10)
                })
            },
            // 商家状态
            switchChange(row,value){
                // 查询商家是否开通了支付功能，判断是否有data
                this.confirmMerchantStatusRow.id = row.id
                if(row.merchantStatus==0){
                    MerchantStatusGo({id: row.id}).then(res => {
                        if(res.success){
                            // this.$message.success({
                            //     message:this.$refs.confirmMerchantStatusRef.open("操作确认","<p style='font-size:12px'>该商户未填写支付配置，是否执行此操作！</p>","warning")
                            // })
                            if(this.data==res.data){
                                return this.$refs.confirmMerchantStatusRef.open("操作确认","<p style='font-size:12px'>该商户未填写支付配置，是否执行此操作！</p>","warning")
                            } else {
                                MerchantStatusGo({id: this.confirmMerchantStatusRow.id,status:0}).then(res => {
                                    if(res.sueccess){
                                        this.$message.success({
                                            // message: value == '1' ? '商家状态更改成功' : '商家状态更改失败',
                                            message:"商家状态上线成功",
                                            duration: 2000,
                                            center:true
                                        })
                                    }
                                    console.log('this.$refs.table',this.$refs.table);
                                    this.$refs.table.load()
                                })
                            }
                        }
                    })
                } else {
                    MerchantStatusDown({id: row.id}).then(res => {
                        if(res.sueccess){
                            this.$message.success({
                                // message: value == '1' ? '商家状态更改成功' : '商家状态更改失败',
                                message:"商家状态下线成功",
                                duration: 2000,
                                center:true
                            })
                        }
                        console.log('this.$refs.table',this.$refs.table);
                        this.$refs.table.load()
                    })
                }
            },
            confirmMerchantStatuTrue(){
                // 点确定的时候更改商家的状态
                if(this.confirmMerchantStatusRow.merchantStatus==0){
                    MerchantStatusGo({id: this.confirmMerchantStatusRow.id,status:0}).then(res => {
                        if(res.sueccess){
                            this.$message.success({
                                // message: value == '1' ? '商家状态更改成功' : '商家状态更改失败',
                                message:"商家状态上线成功",
                                duration: 2000,
                                center:true
                            })
                        }
                            this.$refs.table.load()
                    })
                } 
            },
            payConfigureBut(row){
                this.showPayConfigure = true
                this.editForm.id = row.id
                checkPayConfigure({id:row.id}).then(response =>{
                        if(response.success){
                           this.editForm.merchantNo = response.data.merchantNo
                           this.editForm.terminalId = response.data.terminalId
                           this.editForm.accessToken = response.data.accessToken
                        }
                    })
            },
            closeDialog(){
                // 用dialog的组件一定要这么写，要不然下次点击的时候不弹框
                this.showPayConfigure = false
                this.$refs.ruleForm.resetFields()
            },
            saveDialog(){
                this.$refs.dialogRef.hideLoading()
                this.$refs.ruleForm.validate((valid)=>{
                    if(valid){
                        payConfigure(this.editForm).then(response =>{
                            if(response.success){
                                this.$message.success({message:"配置支付配置成功！",duration:2000,center:true});
                                this.$refs.table.load()
                                this.$refs.ruleForm.resetFields()
                                this.showPayConfigure= false
                                this.$refs.dialogRef.hideLoading()
                            }
                            this.$refs.dialogRef.hideLoading()
                        })
                    }else {
                        this.$refs.dialogRef.hideLoading()
                    }
                })
            },
                    // 重置密码
            resetPwd(index, row) {
                resetpwd({
                    id: row.userId,
                }).then((response) => {
                    if (response.success) {
                    let data = response.data
                    this.$confirm(
                        `您的密码已被修改为<strong>${data}</strong>`,
                        '重置成功',
                        {
                            confirmButtonText: '复制',
                            cancelButtonText: '取消',
                            center: true,
                            type: 'success',
                            closeOnClickModal: false,
                            dangerouslyUseHTMLString: true,
                        },
                    )
                        .then(() => {
                        //创建一个input元素
                        let input = document.createElement('input')
                        //给input的内容复制
                        input.value = data
                        // 在body里面插入这个元素
                        document.body.appendChild(input)
                        // 选中input里面内容
                        input.select()
                        //执行document里面的复制方法
                        document.execCommand('Copy')
                        // 复制之后移除这个元素
                        document.body.removeChild(input)
                        this.$message.success({
                            message: '复制成功',
                            duration: 2000,
                            center: true,
                        })
                        })
                        .catch(() => {})
                    }
                })
                },

        }
    })
</script>

<style scoped lang="scss">
    .marginRight{
        margin-right: 10px;
    }
</style>